(function () {
  // http://www.liulongbin.top:3006/api/getbooks   查询
  // http://www.liulongbin.top:3006/api/addbook     添加
  // http://www.liulongbin.top:3006/api/delbook    删除
  function render() {
    axios.get('http://www.liulongbin.top:3006/api/getbooks').then(res => {
      const data = res.data.data
      const str = data.map(
        ({ id, bookname, author, publisher }) => `
      <tr>
              <th scope="row">${id}</th>
              <td>${bookname}</td>
              <td>${author}</td>
              <td>${publisher}</td>
              <td>
                <button type="button" class="btn btn-link btn-sm" data-id="${id}">删除</button>
              </td>
            </tr>
      `
      ).join('')

      document.querySelector('tbody').innerHTML = str
    })
  }
  render()


  //添加书籍
  document.querySelector('form').addEventListener('submit', function (e) {
    e.preventDefault()
    const bookname = document.querySelector('[name="bookname"]').value
    const author = document.querySelector('[name="author"]').value
    const publisher = document.querySelector('[name="publisher"]').value

    const fd = new FormData()
    console.log(fd);
    // const form = fd.append({' bookname': '张三' })

    // console.log(form);
    // console.log(bookname);
    axios.post('http://www.liulongbin.top:3006/api/addbook', { bookname, author, publisher })
      .then(({ data: { status, msg } }) => {
        if (status != 201) {
          alert(msg)
        }
        render()
        document.querySelector('#addForm').reset()  //重置
      })
  })


  // 删除书籍

  document.querySelector('tbody').addEventListener('click', function (e) {
    if (e.target.tagName === 'BUTTON') {
      console.log(e.target.dataset.id)
      let id = e.target.dataset.id
      axios.delete(`http://www.liulongbin.top:3006/api/delbook?id=${id}`)
        .then(({ data: { status, msg } }) => {
          if (status != 200) {
            alert(msg)
          }
          render()
        })
    }
  })
})()